package org.xworker.model.html;

import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.lang.util.StringUtils;

public class Tag {
    public static String toHtml(ActionContext actionContext) {
        Thing self = actionContext.getObject("self");

        StringBuilder sb = new StringBuilder();
        sb.append("<").append(self.getMetadata().getName());
        String attributes = self.doAction("getAttributes", actionContext);
        if (attributes != null) {
            sb.append(" ").append(attributes);
        }
        sb.append(">\n");

        String content = self.doAction("getContent", actionContext);
        if (content != null) {
            for (Thing child : self.getChilds()) {
                String html = child.doAction("toHtml", actionContext);
                if (html != null) {
                    content = content.replace("%%" + child.getMetadata().getName() + "%%", html);
                }
            }

            content = StringUtils.addLeftPadding(content, null,"    ");
            sb.append(content);
            sb.append("\n");
        }
        sb.append("</").append(self.getMetadata().getName()).append(">").append("\n");

        return sb.toString();
    }
}
